package Filter;

import com.alibaba.fastjson.JSONObject;
import context.BaseContext;
import io.jsonwebtoken.Claims;
import jakarta.servlet.*;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import util.JwtUtils;
import util.Result;

import java.io.IOException;

public class UserLoginFilter implements Filter {
    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest req=(HttpServletRequest) servletRequest;
        HttpServletResponse resp=(HttpServletResponse) servletResponse;

        //1.获取请求url
        String url=req.getRequestURL().toString();
        System.out.println("url为："+url);

        //2.判断请求url中是否含有login，如果包含，说明仕登录操作，放行
        if(url.contains("/login")||url.contains("/register")){
            System.out.println("用户登录操作，放行......");
            filterChain.doFilter(req,resp);
            return;
        }

        //用户浏览商品，放行
        if(url.contains("/user/category")||url.contains("/user/dish")||url.contains("/user/setmeal")){
            System.out.println("用户浏览商品，放行");
            filterChain.doFilter(req,resp);
            return;
        }

        //3获取请求类中的令牌(token)
        String jwt = req.getHeader("token");
        //4.判断令牌是否存在，如果不存在，返回错误结果
        if(jwt==null){
            System.out.println("请求头token为空，返回未登录的信息");
            Result error=Result.error("NOT_LOGIN");
            //手动转换，对象--json------>阿里巴巴fastJSON
            String notLogin = JSONObject.toJSONString(error);
            resp.getWriter().write(notLogin);
            return;
        }

        //5.解析token，如果解析失败，返回错误结果
        try {
            Claims claims= JwtUtils.parseJWT(jwt);
            BaseContext.setCurrentId((Integer) claims.get("id"));
        } catch (Exception e) {//解析失败
            e.printStackTrace();
            Result error=Result.error("NOT_LOGIN");
            //手动转换 对象--JSON ----------->阿里巴巴fastJSON
            String notLogin=JSONObject.toJSONString(error);
            resp.getWriter().write(notLogin);
            return;
        }

        //6.放行
        System.out.println("令牌合法,放行");
        filterChain.doFilter(req,resp);
    }
}
